import os
from pdfminer.high_level import extract_text
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO

UPLOAD_PATH = 'demo/GUI/uploadPath'

def pdf_to_text(pdf_path):
    """
    将PDF文件转换为文本。
    参数:
        pdf_path (str): PDF文件的路径
    返回:
        text (str): 提取的文本内容
    """
    try:
        # 创建资源管理器
        rsrcmgr = PDFResourceManager()
        # 创建一个StringIO对象来接收文本内容
        retstr = StringIO()
        # 创建一个PDF设备对象
        laparams = LAParams()
        # 创建一个PDF转换器对象
        device = TextConverter(rsrcmgr, retstr, laparams=laparams)
        # 创建一个PDF解释器对象
        interpreter = PDFPageInterpreter(rsrcmgr, device)

        # 打开PDF文件
        with open(pdf_path, 'rb') as fp:
            # 遍历每一页
            for page in PDFPage.get_pages(fp):
                interpreter.process_page(page)

        # 获取文本内容
        text = retstr.getvalue()

        # 关闭设备
        device.close()
        retstr.close()

        # 如果文本为空，尝试使用备用方法
        if not text.strip():
            text = extract_text(pdf_path)

        return text if text.strip() else "未能提取到文本内容"

    except Exception as e:
        print(f"转换失败 {pdf_path}: {str(e)}")
        return f"文件转换失败: {str(e)}"

def convert_all_pdfs_to_text():
    """
    将 UPLOAD_PATH 文件夹中的所有 PDF 文件转换为文本并返回合并后的文本内容。
    返回:
        str: 所有PDF文件的合并文本
    """
    if not os.path.exists(UPLOAD_PATH):
        print(f"文件夹 {UPLOAD_PATH} 不存在！")
        return ""

    all_text = []
    for file_name in os.listdir(UPLOAD_PATH):
        if file_name.lower().endswith('.pdf'):
            pdf_path = os.path.join(UPLOAD_PATH, file_name)
            print(f"\n正在转换文件: {file_name}")
            text = pdf_to_text(pdf_path)
            all_text.append(text)
    
    return "\n".join(all_text)

if __name__ == "__main__":
    result_text = convert_all_pdfs_to_text()
    print("\n转换后的知识内容：")
    print("="*50)
    print(result_text)
    print("="*50)
    
    # 将结果保存到临时文件中
    with open('demo/GUI/temp_knowledge.txt', 'w', encoding='utf-8') as f:
        f.write(result_text)